package org.vy.dal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class DALConnector {
	
	private static Properties prop = null;
	
	private static String m_package = "org/vy/dal/dao";
	
	static{
		prop = new Properties();
		FileInputStream fis = null;
		try{
	        fis = new FileInputStream("D:\\VYSofts\\VyManagement\\src\\org\\vy\\dal\\db.properties");
	        prop.load(fis);
		}catch(Exception e){
			e.printStackTrace();
			if(fis != null){
				try{
					fis.close();
				}catch(Exception ex){
					//DO Nothing
					ex.printStackTrace();
				}
			}
		}
    }
	
	public static Connection getConnection() throws SQLException, ClassNotFoundException {
		Class.forName(prop.getProperty("db.driver"));
		Connection dbConn = null;

		if(prop != null)
			dbConn = DriverManager.getConnection(prop.getProperty("db.url"), 
					prop.getProperty("db.user"),
					prop.getProperty("db.password"));

		return dbConn;
	}
	
	public static String createDO(String tblName) throws SQLException, ClassNotFoundException {
		StringBuilder sb = new StringBuilder();
		
		sb.append("package "+ m_package.replaceAll("/", ".")+";\n\n");
		sb.append("import org.vy.dal.common.DBField;\n")
		.append("import org.vy.dal.common.DBTable;\n")
		.append("import org.vy.dal.common.DBSeqGenerator;\n")
		.append("import org.vy.dal.CommonSeqProvider;\n")
		.append("import org.vy.dal.common.BaseDO;\n")
		.append("import java.util.Date;\n\n");
		
		sb.append("@DBTable(\""+ tblName +"\")\n")
		.append("@DBSeqGenerator(org.vy.dal.CommonSeqProvider.class)\n");

		sb.append("public class "+ DALConnector.getMethodSuffix(tblName) +"DO extends BaseDO {\n");
		Connection con = DALConnector.getConnection();
		String sql = "SELECT * FROM " + tblName;
		
		Statement stmt = con.createStatement();
		ResultSet rst = stmt.executeQuery(sql);
		ResultSetMetaData rstMeta = rst.getMetaData();
		int ccount = rstMeta.getColumnCount();
		String fields = "";
		for(int i=1; i <= ccount; i++){
			String columnName = rstMeta.getColumnName(i);
			String columnType = getSqlToJavaType(rstMeta.getColumnType(i));
			String fld = DALConnector.getMethodSuffix(columnName);
			
			fields += "\n\t@DBField(\""+ columnName +"\")\n";
			fields += "\tprivate " + columnType + " m_" + fld +";\n";
			
			sb.append("\tpublic void set" + fld + "( "+ columnType +" value) { \n")
				.append("\t\tm_"+ fld +" = value;\n")
				.append("\t}\n");

			sb.append("\tpublic "+ columnType +" get" + fld + "() { \n")
				.append("\t\treturn m_"+ fld +";\n")
				.append("\t}\n");
		}
		
		sb.append(fields);
		sb.append("}");
		return sb.toString();
	}
	
	private static String getMethodSuffix(String name) {
		name = name.toLowerCase();
		String[] arr = name.split("_");
		name = "";
		for(String a : arr){
			a = a.substring(0,1).toUpperCase() + a.substring(1);
			name += a; 
		}
		return name;
	}
	
	public static String getSqlToJavaType(int type){
		if(java.sql.Types.BIGINT == type){
			return java.lang.Long.class.getSimpleName();
		}else if(java.sql.Types.INTEGER == type
				|| java.sql.Types.SMALLINT == type) {
			return java.lang.Integer.class.getSimpleName();
		}else if(java.sql.Types.DECIMAL == type
				|| java.sql.Types.DOUBLE == type
				|| java.sql.Types.NUMERIC == type) {
			return java.lang.Double.class.getSimpleName();
		}else if(java.sql.Types.FLOAT == type) {
			return java.lang.Float.class.getSimpleName();
		}else if(java.sql.Types.BOOLEAN == type
				|| java.sql.Types.BIT == type) {
			return java.lang.Boolean.class.getSimpleName();
		}else if(java.sql.Types.CHAR == type
				|| java.sql.Types.VARCHAR == type) {
			return java.lang.String.class.getSimpleName();
		}else if(java.sql.Types.BINARY == type) {
			return java.lang.Byte[].class.getSimpleName();
		}else if(java.sql.Types.DATE == type
				|| java.sql.Types.TIME == type
				|| java.sql.Types.TIMESTAMP == type) {
			return java.util.Date.class.getSimpleName();
		}
		return null;
	}
	
	public static void main(String[] s1){
		try{
			Connection con = DALConnector.getConnection();
			String[] s = {"vy_data_upload_job"};
			if(con != null){
				try{
					for(String t1 : s){
						String cls = DALConnector.createDO(t1);
						System.out.println("Connection Success \n" + cls);
						File file = new File("C:/vyrepo/VyManagement/src/"+ m_package +"/");
						if(!file.exists()){
							file.mkdirs();
						}
						file = new File("C:/vyrepo/VyManagement/src/"+ m_package +"/"+ DALConnector.getMethodSuffix(t1) +"DO.java");
						if(!file.exists()){
							file.createNewFile();
						}
						FileWriter fw = new FileWriter(file);
						fw.write(cls);
						fw.close();
					}
				}catch(Exception ex){
					ex.printStackTrace();
				}
			}
		}catch(Exception e){
			System.out.println("Connection Failure :: "+ e.getMessage());
			e.printStackTrace();
		}
	}
}
